package com.example.etwzgzxt.view.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Toast;

import com.example.etwzgzxt.R;
import com.example.etwzgzxt.adapter.MessageListAdapter;
import com.example.etwzgzxt.bean.MessageInfo;
import com.example.etwzgzxt.tool.HttpHelper;
import com.example.etwzgzxt.tool.InfoApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.message.BasicNameValuePair;

public class DeviceMessageActivity extends AppCompatActivity {


    public static final int GET_LIST = 1;
    public static final int DELETE = 2;

    ListView listView;
    MessageListAdapter adapter;
    List<MessageInfo> items = new ArrayList<>();
    String dateBegin = null;
    String dateEnd = null;
    String deviceId = null;

    int year = 2016;
    int monthOfYear = 5;
    int dayOfMonth = 5;

    String deviceCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_message);

        Intent intent  = getIntent();
        deviceCode = intent.getStringExtra("deviceCode");
        listView = (ListView) findViewById(R.id.listmessage);
      adapter = new MessageListAdapter(this, items);
        listView.setAdapter(adapter);
        DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
        datePicker.init(year, monthOfYear - 1, dayOfMonth, new DatePicker.OnDateChangedListener(){

            public void onDateChanged(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                dateBegin = year + "-" + (monthOfYear + 1)+ "-" + dayOfMonth;
                new BackgroundTask(GET_LIST).execute();
            }
        });
        DatePicker datePicker1 = (DatePicker) findViewById(R.id.datePicker1);
        datePicker1.init(year, monthOfYear - 1, dayOfMonth, new DatePicker.OnDateChangedListener(){

            public void onDateChanged(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                dateEnd = year + "-" + (monthOfYear + 1)+ "-" + dayOfMonth;
                new BackgroundTask(GET_LIST).execute();
            }
        });
       // new BackgroundTask(GET_LIST).execute();
    }

    public void btnDelete(View view) {
        new BackgroundTask(DELETE).execute();
    }

    public class BackgroundTask extends AsyncTask<Void, Void, String> {

        int type;

        public BackgroundTask(int type) {
            this.type = type;
        }

        @Override
        protected String doInBackground(Void... params) {
            if (type == GET_LIST) {
                return getList();
            } else {
                return delete();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            parseResult(result, type);
        }
    }

    public String getList() {
        String baseURL =    ((InfoApplication)getApplicationContext()).getBasehost()+"/device/getoneinfo.do";

        List<NameValuePair> pair = new ArrayList<>();
        pair.add( new BasicNameValuePair("access_token", ((InfoApplication) getApplication()).getAccess_token()));
        pair.add(new BasicNameValuePair("devicecode", deviceCode));

       // dateEnd+="  00:00:00";
        if(dateBegin!=null) {
            if (!dateBegin.endsWith("00:00:00"))
                dateBegin += "  00:00:00";
            pair.add(new BasicNameValuePair("dateBegin", dateBegin));
        }
        else
        return  null;
        if(dateEnd!=null) {
            if (!dateEnd.endsWith("00:00:00"))
                dateEnd += "  00:00:00";
            pair.add(new BasicNameValuePair("dateEnd", dateEnd));
        }
        else
        return  null;
        for (NameValuePair pairs: pair) {
            System.out.println(pairs.getName()+" "+pairs.getValue());
        }


        return new HttpHelper().post(baseURL, pair);
    }

    public String delete() {
        String baseURL =  ((InfoApplication)getApplicationContext()).getBasehost()+"/device/deletebytime.do";
        List<NameValuePair> pair = new ArrayList<>();
        pair.add( new BasicNameValuePair("access_token", ((InfoApplication) getApplication()).getAccess_token()));
        pair.add(new BasicNameValuePair("devicecode", deviceCode));

        dateBegin+="  00:00:00";
        dateEnd+="  00:00:00";
        if(dateBegin!=null)
            pair.add(new BasicNameValuePair("dateBegin", dateBegin));
        if(dateEnd!=null)
            pair.add( new BasicNameValuePair("dateEnd", dateEnd));

        for (NameValuePair pairs: pair) {
            System.out.println(pairs.getName()+" "+pairs.getValue());
        }
        return new HttpHelper().post(baseURL, pair);
    }

    public void parseResult(String result, int type) {
        if(result==null)
            return;
        try {

            JSONObject jsonObject = new JSONObject(result);
            switch (jsonObject.getInt("code")) {
                case 200:
                    if (type == GET_LIST) {
                        try {
                            
                           // jsonObject = jsonObject.getJSONObject("result");
                            if(jsonObject!=null)
                            {
                                JSONObject device=  new JSONObject(jsonObject.getString("result"));
                                JSONArray jsonArray = new JSONArray(device.getString("messages"));
                                int length = jsonArray.length();
                                items.clear();
                                for (int i = 0; i < length; i++) {
                                    jsonObject = jsonArray.getJSONObject(i);
                                    items.add(new MessageInfo(jsonObject.optString("messageid"),jsonObject.optString("happendtime"), jsonObject.optString("latitude"),  jsonObject.optString("longtitude")));

                                }
                                for (MessageInfo item : items) {
                                    System.out.println(item.toString());
                                }

                                adapter.updateData(items);
                                adapter.notifyDataSetChanged();
                            }
                            else
                                Toast.makeText(this,"没有信息",Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
                        new BackgroundTask(GET_LIST).execute();
                    }
                    break;
                case 403:
                    Toast.makeText(this, "Not Acceptable", Toast.LENGTH_SHORT).show();
                    break;
                case 406:
                    Toast.makeText(this, "Forbidden", Toast.LENGTH_SHORT).show();
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (result == null) {
            Toast.makeText(this, "请检查网络设置", Toast.LENGTH_SHORT).show();
            return;
        }

    }

}
